package com.rlz.base.tools.rxbus

import com.rlz.base.util.single.Single
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject

/**
 * Created by RLZ
 * on 2021/11/3
 *
 */
class RxBus {

    companion object : Single<RxBus>(::RxBus)

    private var mBus: Subject<Any> = PublishSubject.create<Any>().toSerialized()

    fun send(any: Any) {
        mBus.onNext(any)
    }

    fun of(): Observable<Any> {
        return mBus
    }

    fun <T> of(type: Class<T>): Observable<T> {
        return mBus.ofType(type)
    }

    fun post(code: Int, any: Any) {
        mBus.onNext(Event(code, any))
    }

    fun <T> to(code: Int, event: Class<T>): Observable<T> {
        return mBus.ofType(Event::class.java)
            .filter { e ->
                e.code == code && event.isInstance(e.any)
            }.map { e ->
                e.any
            }.cast(event)
    }

    fun hasObservers(): Boolean {
        return mBus.hasObservers()
    }
}